﻿using System;

namespace Octopus.Injection.Commons
{
    public static class Injector
    {
        public static object InjectService(string serviceBlock, Type dependency = null)
        {
            object res = null;

            if(ConfigRepository.ServiceBlocks.ContainsKey(serviceBlock))
            {
                var injType = ConfigRepository.ServiceBlocks[serviceBlock].InjectionType;

                if (dependency != null)
                {
                    var genParam = new Type[1];
                    genParam[0] = dependency;

                    injType = injType.MakeGenericType(genParam);
                }
                
                res = Activator.CreateInstance(injType, null);
            }

            return res;
        }
        
        public static object InjectService<T>(string serviceBlock)
        {
            return InjectService(serviceBlock, typeof(T));
        }
    
        public static T Intance<T>()
        {
            T res = default(T);
            Type gType = typeof (T);

            if (!string.IsNullOrEmpty(gType.AssemblyQualifiedName) && ConfigRepository.InjectionMap.ContainsKey(gType.AssemblyQualifiedName))
            {
                res = (T)ConfigRepository.InjectionMap[gType.AssemblyQualifiedName];
            }

            return res;
        }
    }
}
